package com.stadium.web.controller;

import com.fastsite.common.api.ApiResult;
import com.fastsite.common.api.ApiSecured;
import com.fastsite.common.api.ApiTokenUser;
import com.fastsite.common.domain.TokenUserObject;
import com.fastsite.common.enums.StatusEnum;
import com.stadium.web.domain.Reserve;
import com.stadium.web.domain.User;
import com.stadium.web.service.ReserveService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.Authorization;
import lombok.Data;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.List;


/**
 * 预定对象 reserve
 *
 * @author ruoyi
 * @date 2020-03-15
 */
@Validated
@Api(tags = "预定管理")
@RestController
@RequestMapping("/web/reserve")
public class ReserveController {

    @Autowired
    private ReserveService reserveService;

    /**
     * 列表页面
     */
    @ApiOperation("预定列表信息")
    @ApiImplicitParams({
    @ApiImplicitParam(name="page",value="当前页数",required=false,paramType="form",dataType="Long"),
    @ApiImplicitParam(name="size",value="每页的数量",required=false,paramType="form",dataType="Long"),
    @ApiImplicitParam(name="venueId",value="预定场馆",required=false,paramType="form",dataType="Long"),
    @ApiImplicitParam(name="userId",value="预定人",required=false,paramType="form",dataType="Date"),
    @ApiImplicitParam(name="reserveTime",value="预定时间",required=false,paramType="form",dataType="Date"),
    })
    @GetMapping("/list")
    public ApiResult index(@ApiIgnore Reserve reserve){

        // 创建匹配器，进行动态查询匹配
        ExampleMatcher matcher = ExampleMatcher.matching();

        // 获取预定列表
        Example<Reserve> example = Example.of(reserve, matcher);
        Page<Reserve> list = reserveService.getPageList(example);

        HashMap<String,Object> result = new HashMap<>();
        result.put("list", list.getContent());
        result.put("page", list);
        // 封装数据
        return ApiResult.ok(result,"获取预定列表信息");
    }

    /**
     * 跳转到编辑页面
     */
    @ApiOperation("单个预定信息")
    @GetMapping("/getOneReserve")
    public ApiResult getOneReserve(@RequestParam("id") Long id){
        Reserve reserve=  reserveService.getById(id);
        return ApiResult.ok(reserve,"获取单个预定");
    }

    /**
     * 保存添加/修改的数据
     * @param reserveFrom 实体对象
     */
    @ApiOperation(value = "保存单个预定", authorizations = @Authorization(value = "token"), produces =  MediaType.APPLICATION_JSON_UTF8_VALUE)
//    @ApiImplicitParams({
//    @ApiImplicitParam(name="id",value="ID",required=false,paramType="body",dataType="Long"),
//    @ApiImplicitParam(name="venueId",value="预定场馆",required=false,paramType="body",dataType="Long"),
////    @ApiImplicitParam(name="userId",value="预定人",required=false,paramType="body",dataType="Date"),
////    @ApiImplicitParam(name="reserveTime",value="预定时间",required=false,paramType="body",dataType="Date"),
//    })
    @ApiSecured
    @PostMapping({"/save"})
    public ApiResult save(@ApiIgnore @ApiTokenUser TokenUserObject<User> user, @Valid @RequestBody ReserveForm reserveFrom){
        Reserve reserve = null;
        if(!StringUtils.isEmpty(reserveFrom.getId())){
            //修改
//            reserve = reserveService.getById(reserveFrom.getId());
//
//            reserve.setId(reserveFrom.getId());
//            reserve.setVenueId(reserveFrom.getVenueId());
//            reserve.setUserId(reserveFrom.getUserId());
//            reserve.setReserveTime(reserveFrom.getReserveTime());
            }else{
            //新增
            reserve = new Reserve();
            BeanUtils.copyProperties(reserveFrom,reserve);
            reserve.setUserId(user.getId());
            reserve.setVenueId(reserveFrom.getVenueId());
        }
        // 预定场馆
        reserveService.reserveVenue(reserve,user.getUser());
        return ApiResult.ok(reserve,"保存成功");
    }
    /**
     * 保存添加/修改的数据
     * @param reserveFrom 实体对象
     */
    @ApiOperation(value = "保存多个预定", authorizations = @Authorization(value = "token"), produces =  MediaType.APPLICATION_JSON_UTF8_VALUE)
//    @ApiImplicitParams({
//    @ApiImplicitParam(name="id",value="ID",required=false,paramType="body",dataType="Long"),
//    @ApiImplicitParam(name="venueId",value="预定场馆",required=false,paramType="body",dataType="Long"),
////    @ApiImplicitParam(name="userId",value="预定人",required=false,paramType="body",dataType="Date"),
////    @ApiImplicitParam(name="reserveTime",value="预定时间",required=false,paramType="body",dataType="Date"),
//    })
    @ApiSecured
    @PostMapping({"/saveArr"})
    public ApiResult save(@ApiIgnore @ApiTokenUser TokenUserObject<User> user, @Valid @RequestBody ReserveArrForm reserveArrForm){
        for(Long venueId:reserveArrForm.getVenueIds()){
            //新增
            Reserve reserve = new Reserve();
            reserve.setUserId(user.getId());
            reserve.setVenueId(venueId);
             // 预定场馆
            reserveService.reserveVenue(reserve,user.getUser());
        }
        return ApiResult.ok("保存成功");
    }
    /**
     * 获取用户预定信息
     */
    @ApiSecured
    @ApiOperation("获取用户预定信息")
    @GetMapping("/getUserReserveVenue")
    public ApiResult getUserReserveVenue(@ApiIgnore @ApiTokenUser TokenUserObject<User> user){
        List<Reserve> reserves =  reserveService.getByUserId(user.getId());
        return ApiResult.ok(reserves,"获取用户预定信息");
    }

    /**
     * 设置一条或者多条数据的状态
     */

    @ApiOperation(value = "修改预定状态",hidden=true)
    @ApiImplicitParams({
            @ApiImplicitParam(name="param",value="状态（1:正常，2:冻结,3:删除）",required=true,paramType="path",dataType="String"),
            @ApiImplicitParam(name="ids",value="修改[id]",required=true,paramType="form",dataType="List")}
    )
    @RequestMapping(value = "/status/{param}",method={RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public ApiResult status(
            @PathVariable("param") String param,
            @RequestParam(value = "ids", required = false) List<Long> ids){
        // 更新状态
        StatusEnum statusEnum = StatusEnum.getByCode(Byte.parseByte(param));
        if (reserveService.updateStatus(statusEnum, ids)) {
            return ApiResult.ok(statusEnum.getMessage() + "成功");
        } else {
            return ApiResult.err(statusEnum.getMessage() + "失败，请重新操作");
        }
    }
}
@Data
@ApiModel("场馆预定Form")
class ReserveForm{
    @ApiModelProperty(value = "ID")
    private Long id;

    /** 预定场馆 */
    @ApiModelProperty(value = "预定场馆",required = true)
    @NotNull(message = "未选择场馆")
    private Long venueId;
}

@Data
@ApiModel("场馆预定Form")
class ReserveArrForm{
    /** 预定场馆 */
    @ApiModelProperty(value = "预定场馆",required = true)
    @NotNull(message = "未选择场馆")
    private List<Long> venueIds;
}